﻿namespace langsamu.PlaceholdIt.Web.UI.WebControls
{
	public class Image : System.Web.UI.WebControls.Image
	{
		public override string ImageUrl
		{
			get
			{
				if (string.IsNullOrEmpty(base.ImageUrl))
				{
					return PlaceholdItImageUrl;
				}
				else
				{
					return base.ImageUrl;
				}
			}
			set
			{
				base.ImageUrl = value;
			}
		}
		public override System.Web.UI.WebControls.Unit Width
		{
			get
			{
				if (string.IsNullOrEmpty(base.ImageUrl) && base.Width.IsEmpty)
				{
					return System.Web.UI.WebControls.Unit.Pixel(300);
				}
				else
				{
					return base.Width;
				}
			}
			set
			{
				base.Width = value;
			}
		}
		public ImageFormat ImageFormat
		{
			get
			{
				return (ImageFormat)ViewState["ImageFormat"];
			}
			set
			{
				ViewState["ImageFormat"] = value;
			}
		}

		private string PlaceholdItImageUrl
		{
			get
			{
				var urlBuilder = new System.Text.StringBuilder();

				urlBuilder.Append("http://placehold.it");

				urlBuilder.Append(this.Width.Value);

				if (!base.Height.IsEmpty)
				{
					urlBuilder.AppendFormat("x{0}", base.Height.Value);
				}

				if (ImageFormat != PlaceholdIt.ImageFormat.gif)
				{
					urlBuilder.AppendFormat(".{0}", ImageFormat);
				}

				if (!base.BackColor.IsEmpty)
				{
					urlBuilder.AppendFormat("x{0}", ToHtmlHexColor(base.BackColor));
				}
				else if (!base.ForeColor.IsEmpty)
				{
					urlBuilder.Append("/cccccc");
				}

				if (!base.ForeColor.IsEmpty)
				{
					urlBuilder.AppendFormat("/{0}", ToHtmlHexColor(base.ForeColor));
				}

				if (!string.IsNullOrEmpty(base.AlternateText))
				{
					urlBuilder.AppendFormat("&text={0}", base.AlternateText);
				}
				else if (!string.IsNullOrEmpty(base.ToolTip))
				{
					urlBuilder.AppendFormat("&text={0}", base.ToolTip);
				}

				return urlBuilder.ToString();
			}
		}
		private string ToHtmlHexColor(System.Drawing.Color original)
		{
			return string.Format("{0:X2}{1:X2}{2:X2}", original.R, original.G, original.B);
		}
	}
}
